package pers.whj.stack;

import java.lang.reflect.Array;

public class Stack<T> {
    private static final int DEFAULT_SIZE = 16;
    private final int mMaxSize;
    private int mTop;
    private T[] mData;

    public Stack() {
        this(DEFAULT_SIZE);
    }

    public Stack(int size) {
        if (size <= 0) {
            size = DEFAULT_SIZE;
        }
        mMaxSize = size;
        mTop = -1;
    }

    public boolean isEmpty() {
        return mTop == -1;
    }

    public boolean isFull() {
        return mTop == mMaxSize - 1;
    }

    public boolean push(T data) {
        if (mData == null) {
            mData = (T[]) Array.newInstance(data.getClass(), mMaxSize);
        }
        if (!isFull()) {
            mTop++;
            mData[mTop] = data;
            return true;
        } else {
            return false;
        }
    }

    public T pop() {
        if (isEmpty()) {
            return null;
        } else {
            mTop--;
            return mData[mTop + 1];
        }
    }

    public T getTop() {
        if (isEmpty()) {
            return null;
        } else {
            return mData[mTop];
        }
    }
}